module Shamela
  module Common
    class << self
    
      MAP_FILENAME = File.join(File.dirname(__FILE__), 'map')
      # Read translation map
      def read_map
        map = File.read(MAP_FILENAME).split /[\r\n]/
        latin_to_arabic = {}
        map.each do |line|
          next if line.length == 0
          arabic, latin = line.split
          latin_to_arabic[latin] = arabic
        end
        latin_to_arabic
      end
      
      def decode(encoded)
        undefined_chars = []
        decoded = ""
        encoded.each_char do |latin_char|
          arabic_char = @@map[latin_char]
          if arabic_char
            decoded << arabic_char
          else
            undefined_chars << latin_char
            decoded << latin_char
          end
        end
        warn("Found characters that cannot be translated: #{undefined_chars.uniq.sort.inspect}")
        decoded
      end
    end

    # Store map in a class variable
    @@map = read_map
  end
end
